package com.lemo.smart.helper;

import com.lemo.smart.annotation.Inject;
import com.lemo.smart.util.ReflectionUtil;

import org.apache.commons.lang.ArrayUtils;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Objects;

/**
 * 依赖注入助手类
 * Created by 罗选通 on 2017/12/22.
 */
public final class IocHelper {

  static {
    //获取所有bean与bean实例的映射关系
    Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
    if (!beanMap.isEmpty()) {
      for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
        //从beanmap中获取bean和bean实例
        Class<?> beanClass = beanEntry.getKey();
        Object beanInstance = beanEntry.getValue();
        //获取bean内定义的所有成员变量
        Field[] fields = beanClass.getDeclaredFields();
        if (!ArrayUtils.isEmpty(fields)) {
          //遍历field
          for (Field field : fields) {
            //判断当前Field是否含有Inject注解
            if (field.isAnnotationPresent(Inject.class)) {
              //在beanmap中获取对应的bean实例
              Class<?> type = field.getType();
              Object o = beanMap.get(type);
              if (Objects.nonNull(o)) {
                //通过反射初始化beanField的值
                ReflectionUtil.setField(beanInstance, field, o);
              }
            }
          }
        }
      }
    }
  }
}
